#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2021/10/09 09:11:01
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import os
import click
from flask import Flask
from app.fakes import fake_role
from app.main import main_bp
from app.auth import auth_bp
from app.user import user_bp
from app.ext import db,bootstrap,login_manager,moment,migrate,mail,avatars
from app.models import User,Role
#导入config
from configs import config  

def create_app():
    ## 创建app实例
    app = Flask(__name__)
    # 设置从config中导入设置
    app.config.from_object(config['development'])
    register_blueprints(app)
    register_extensions(app)
    register_shell_context(app)
    register_commands(app)
    return app


def register_blueprints(app):
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(user_bp, url_prefix='/user')
    # app.register_blueprint(errors_bp)


def register_extensions(app):
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    migrate.init_app(app, db)
    avatars.init_app(app)

def register_shell_context(app):
    @app.shell_context_processor
    def make_shell_context():
        return dict(db=db, User=User,Role=Role)



def register_commands(app):
    @app.cli.command()
    @click.option('--users', default=10, help='Quantity of users, default is 10.')
    def forge(users):
        """Generate fake data."""
        from app.fakes import fake_user,fake_role

        db.drop_all()
        db.create_all()
        #生产角色列表
        click.echo('Generating the roles...')
        fake_role()
        #生产虚拟user_name
        click.echo('Generating the users...')
        fake_user(users)
        
        click.echo('Done.')

#定义用户加载器
@login_manager.user_loader
def load_user(id):
    return User.query.get(id)






